use crate::config::API_BASE_URL;
use crate::entities::{ApiResponse, UploadData, FishingCircleRequest};
use reqwest::{Client, multipart};
use std::collections::HashMap;
use tokio::fs;

pub struct ApiClient {
    client: Client,
    base_url: String,
}

impl ApiClient {
    pub fn new() -> Self {
        let client = Client::new();
        Self {
            client,
            base_url: API_BASE_URL.to_string(),
        }
    }
    
    pub async fn check_server_health(&self) -> Result<bool, String> {
        let url = format!("{}/health", self.base_url);
        
        match self.client.get(&url).send().await {
            Ok(response) => Ok(response.status().is_success()),
            Err(_) => Ok(false)
        }
    }

    pub async fn upload_file(&self, file_path: &str, jwt_token: &str) -> Result<UploadData, String> {
        let file_bytes = fs::read(file_path).await
            .map_err(|e| format!("Failed to read file: {}", e))?;

        let file_name = std::path::Path::new(file_path)
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("upload.jpg");

        // 创建multipart表单数据
        let form = multipart::Form::new()
            .part("file", multipart::Part::bytes(file_bytes)
                .file_name(file_name.to_string()));

        let url = format!("{}/file/upload", self.base_url);

        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .multipart(form)
            .send()
            .await
            .map_err(|e| format!("Upload failed: {}", e))?;

        let _status = response.status();
        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应，请检查服务器状态".to_string());
        }
        
        let api_response: ApiResponse<UploadData> = serde_json::from_str(&response_text)
            .map_err(|e| format!("响应格式错误: {}\n原始响应: {}", e, response_text))?;

        if api_response.status != 1 && api_response.code != 200 {
            return Err(api_response.msg);
        }

        api_response.data.ok_or("No data in response".to_string())
    }

    pub async fn get(&self, endpoint: &str, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}{}", self.base_url, endpoint);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Request failed: {}", e))?;

        response.text().await.map_err(|e| format!("Failed to read response: {}", e))
    }

    pub async fn post(&self, endpoint: &str, data: &HashMap<&str, &str>, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}{}", self.base_url, endpoint);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(data)
            .send()
            .await
            .map_err(|e| format!("Request failed: {}", e))?;

        response.text().await.map_err(|e| format!("Failed to read response: {}", e))
    }

    pub async fn save_fishing_circle(&self, circle: &FishingCircleRequest, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/circle/add", self.base_url);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(circle)
            .send()
            .await
            .map_err(|e| format!("Failed to save fishing circle: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }
        
        Ok(response_text)
    }

    pub async fn get_fishing_circles(&self, page: u32, size: u32, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/list?pageNum={}&pageSize={}", self.base_url, page, size);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get fishing circles: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        // 解析JSON响应
        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    // 获取协议列表
    pub async fn get_agreements(&self, page_num: u32, page_size: u32, type_filter: String, enabled_filter: String, jwt_token: &str) -> Result<String, String> {
        let mut url = format!("{}/settings/agr/all?pageNum={}&pageSize={}", self.base_url, page_num, page_size);
        
        // 添加可选的筛选条件
        if !type_filter.is_empty() {
            url.push_str(&format!("&type={}", type_filter));
        }
        if !enabled_filter.is_empty() {
            url.push_str(&format!("&enabled={}", enabled_filter));
        }
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get agreements: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn get_fishing_circle_detail(&self, id: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/get?id={}", self.base_url, id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get fishing circle detail: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn mark_circle_active(&self, id: String, is_active: i32, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/circle/markActive?id={}&isActive={}", self.base_url, id, is_active);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to mark circle active: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn delete_fishing_circle(&self, id: String, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/circle/delete?id={}", self.base_url, id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to delete fishing circle: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn update_fishing_circle(&self, id: String, title: String, description: String, pics: Vec<String>, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/circle/update", self.base_url);
        
        let mut request_body = serde_json::Map::new();
        request_body.insert("id".to_string(), serde_json::Value::String(id));
        request_body.insert("title".to_string(), serde_json::Value::String(title));
        request_body.insert("description".to_string(), serde_json::Value::String(description));
        request_body.insert("pics".to_string(), serde_json::Value::Array(
            pics.into_iter().map(serde_json::Value::String).collect()
        ));

        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(&request_body)
            .send()
            .await
            .map_err(|e| format!("Failed to update fishing circle: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn get_circle_match(&self, circle_id: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/match?id={}", self.base_url, circle_id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get circle match: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn save_circle_match(&self, circle_id: String, spot_ids: Vec<String>, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/circle/save_match", self.base_url);
        
        let circle_id_num = circle_id.parse::<i64>().map_err(|e| format!("Invalid circle ID: {}", e))?;
        let spot_ids_nums: Vec<i64> = spot_ids
            .into_iter()
            .map(|id| id.parse::<i64>().map_err(|e| format!("Invalid spot ID: {}", e)))
            .collect::<Result<_, _>>()?;

        let mut request_body = serde_json::Map::new();
        request_body.insert("id".to_string(), serde_json::Value::Number(serde_json::Number::from(circle_id_num)));
        request_body.insert("spotIds".to_string(), serde_json::Value::Array(
            spot_ids_nums.into_iter().map(|id| serde_json::Value::Number(serde_json::Number::from(id))).collect()
        ));

        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(&request_body)
            .send()
            .await
            .map_err(|e| format!("Failed to save circle match: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn get_circle_messages(&self, city_code: String,  cursor: Option<String>, size: u32, jwt_token: &str) -> Result<serde_json::Value, String> {
        let mut url = format!("{}/circle-messages/quasi-realtime?cityCode={}&size={}", self.base_url, city_code, size);
        
        if let Some(cursor) = cursor {
            url.push_str(&format!("&cursor={}", cursor));
        }
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get circle messages: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn get_circle_spots(&self, circle_id: String, page: u32, size: u32, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/spots?id={}&pageNum={}&pageSize={}", self.base_url, circle_id, page, size);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get circle spots: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    
    pub async fn search_cities(&self, page_num: u32, page_size: u32, city: &str, jwt_token: &str) -> Result<serde_json::Value, String> {
        let mut url = format!("{}/circle/cities/page?pageNum={}&pageSize={}", self.base_url, page_num, page_size);
        
        // 如果提供了城市搜索关键词，则添加到URL参数中
        if !city.is_empty() {
            url = format!("{url}&city={}", city);
        }
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get circle cities: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

      pub async fn get_circle_cities(&self, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/getCities", self.base_url);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get circle cities: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn add_circle_city(&self, city_code: &str, city_name: &str, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/cities/add", self.base_url);
        
        // 创建请求数据
        let mut data = HashMap::new();
        data.insert("cityCode", city_code);
        data.insert("city", city_name);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(&data)
            .send()
            .await
            .map_err(|e| format!("Failed to add circle city: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn refresh_cities(&self, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/refreshCities", self.base_url);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to refresh cities: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }
    
    pub async fn add_spot(&self, spot_data: &serde_json::Value, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/add", self.base_url);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(spot_data)
            .send()
            .await
            .map_err(|e| format!("Failed to add spot: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn search_circle_cities(&self, keyword: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/circle/searchCities?keyword={}", self.base_url, keyword);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to search circle cities: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn get_users(&self, page: u32, size: u32, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/user/page?pageNum={}&pageSize={}", self.base_url, page, size);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get users: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn create_user(&self, user_data: &HashMap<&str, &str>, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/user/register", self.base_url);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .json(user_data)
            .send()
            .await
            .map_err(|e| format!("Failed to create user: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn delete_user(&self, user_id: u64, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/user/{}", self.base_url, user_id);
        
        let response = self.client
            .delete(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to delete user: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn enable_user(&self, user_id: String, status: i32, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/user/enable?status={}&id={}", self.base_url, status, user_id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to enable/disable user: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn switch_admin_role(&self, user_id: String, is_admin: i32, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/user/switch?userId={}&isAdmin={}", self.base_url, user_id, is_admin);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to switch admin role: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    pub async fn search_users(&self, username: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/user/search?username={}", self.base_url, username);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to search users: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn get_spots(&self, query: &str, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/list?{}", self.base_url, query);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get spots: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn get_fishing_spot_by_id(&self, id: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/getSpot?spotId={}", self.base_url, id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get fishing spot by id: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn toggle_spot_disabled(&self, spot_id: String, disabled: bool, jwt_token: &str) -> Result<bool, String> {
        use crate::entities::ApiResponse;

        let url = format!("{}/spot/{}/toggle?disabled={}", self.base_url, spot_id, disabled);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to toggle spot status: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let api_response: ApiResponse<i32> = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        if api_response.status == 1 {
            let result = api_response.data.unwrap_or(0) != 0;
            Ok(result)
        } else {
            let message = api_response.msg;
            if message.is_empty() {
                Err("操作失败".to_string())
            } else {
                Err(message)
            }
        }
    }

    pub async fn get_collected_spots(&self, page: u32, size: u32, is_collected: u32, spot_id: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/public/collected?pageNum={}&pageSize={}&isCollected={}&spotId={}", 
                         self.base_url, page, size, is_collected, spot_id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get collected spots: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    pub async fn get_spot_harvests(&self, page: u32, size: u32, spot_id: String, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/getSpotHarvests?pageNum={}&pageSize={}&spotId={}", 
                         self.base_url, page, size, spot_id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get spot harvests: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    // 获取等级设置列表
    pub async fn get_level_rules(&self, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/levelRules", self.base_url);
        
        println!("[DEBUG] Making HTTP request to: {}", url);
        println!("[DEBUG] Using JWT token: {}...", &jwt_token[..std::cmp::min(20, jwt_token.len())]);
        
        let response = match self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] HTTP request failed: {}", e);
                    return Err(format!("Failed to get level rules: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Successfully read response text, length: {} characters", text.len());
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read response text: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        // Debug: Print the raw response text
        println!("[DEBUG] Level Rules API Response Text: {}", response_text);
        println!("[DEBUG] Response length: {} characters", response_text.len());
        
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        // Try to handle malformed response with multiple JSON objects
        let cleaned_response = if response_text.contains("}{")
        {
            println!("[DEBUG] Detected concatenated JSON responses, attempting to extract first valid JSON");
            
            // Split by }{ and try to parse the first part
            let parts: Vec<&str> = response_text.split("}{")
                .collect();
            
            if let Some(first_part) = parts.first() {
                let mut first_json = first_part.to_string();
                if !first_json.ends_with('}') {
                    first_json.push('}');
                }
                
                println!("[DEBUG] Attempting to parse first JSON part: {}", first_json);
                
                // Try to parse the first JSON
                match serde_json::from_str::<serde_json::Value>(&first_json) {
                    Ok(parsed) => {
                        println!("[DEBUG] Successfully parsed first JSON part");
                        return Ok(parsed);
                    }
                    Err(e) => {
                        println!("[DEBUG] Failed to parse first JSON part: {}", e);
                    }
                }
            }
            
            // If that fails, try the second part
            if parts.len() > 1 {
                let second_part = format!("{{{}", parts[1]);
                println!("[DEBUG] Attempting to parse second JSON part: {}", second_part);
                
                match serde_json::from_str::<serde_json::Value>(&second_part) {
                    Ok(parsed) => {
                        // Check if this is an error response
                        if let Some(status) = parsed.get("status") {
                            if status == 0 {
                                if let Some(msg) = parsed.get("msg") {
                                    return Err(format!("API Error: {}", msg.as_str().unwrap_or("Unknown error")));
                                }
                            }
                        }
                        return Ok(parsed);
                    }
                    Err(e) => {
                        println!("[DEBUG] Failed to parse second JSON part: {}", e);
                    }
                }
            }
            
            // If all parsing attempts fail, return the original response for standard parsing
            response_text
        } else {
            response_text
        };

        let parsed: serde_json::Value = serde_json::from_str(&cleaned_response)
            .map_err(|e| {
                println!("[ERROR] JSON Parse Error: {}", e);
                println!("[ERROR] Raw response causing parse error: '{}'", cleaned_response);
                format!("Failed to parse response: {} | Raw response: {}", e, cleaned_response)
            })?;

        Ok(parsed)
    }

    // 获取钓点表单属性
    pub async fn get_spot_props(&self, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/spot/getProps", self.base_url);
        
        println!("[DEBUG] Making HTTP request to: {}", url);
        println!("[DEBUG] Using JWT token: {}...", &jwt_token[..std::cmp::min(20, jwt_token.len())]);
        
        let response = match self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] HTTP request failed: {}", e);
                    return Err(format!("Failed to get spot props: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Successfully read response text, length: {} characters", text.len());
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read response text: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| format!("Failed to parse response: {}", e))?;

        Ok(parsed)
    }

    // 更新协议状态
    pub async fn update_agreement_status(&self, id: String, enabled: String, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/settings/agr/enable?id={}&enabled={}", self.base_url, id, enabled);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to update agreement status: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    // 获取新版本协议内容
    pub async fn get_new_version_content(&self, id: String, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/settings/agr/newVersion?id={}", self.base_url, id);
        
        let response = self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await
            .map_err(|e| format!("Failed to get new version content: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }

    // 更新协议或创建新版本
    pub async fn update_agreement(&self, id: String, content: String,jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/settings/agr/updateAgr", self.base_url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("content", content);
        body.insert("id", id);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| format!("Failed to update agreement: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }
    
    // 新增协议
    pub async fn add_new_agreement(&self, type_param: String, content: String, jwt_token: &str) -> Result<String, String> {
        let url = format!("{}/settings/agr/saveAgr", self.base_url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("type", type_param);
        body.insert("content", content);
        
        let response = self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| format!("Failed to add new agreement: {}", e))?;

        let response_text = response
            .text()
            .await
            .map_err(|e| format!("Failed to read response: {}", e))?;
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        Ok(response_text)
    }
    
    // 添加等级规则
    pub async fn add_level_rule(
        &self, 
        level_name: String,
        min_points: String,
        max_points: String,
        core_trait: String,
        uri: String,
        upgrade_threshold: String,
        jwt_token: &str
    ) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/levelRules", self.base_url);
        
        println!("[DEBUG] Adding level rule to: {}", url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("levelName", level_name);
        body.insert("minPoints", min_points);
        body.insert("maxPoints", max_points);
        body.insert("coreTrait", core_trait);
        body.insert("uri", uri);
        body.insert("upgradeThreshold", upgrade_threshold);
        
        let response = match self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] Add level rule HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] Add level rule HTTP request failed: {}", e);
                    return Err(format!("Failed to add level rule: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Add level rule response text: {}", text);
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read add level rule response: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| {
                println!("[ERROR] Add level rule JSON Parse Error: {}", e);
                println!("[ERROR] Raw response: '{}'", response_text);
                format!("Failed to parse response: {} | Raw response: {}", e, response_text)
            })?;

        Ok(parsed)
    }
    
    // 更新等级规则
    pub async fn update_level_rule(
        &self, 
        level_id: String,
        level_name: String,
        min_points: String,
        max_points: String,
        core_trait: String,
        uri: String,
        upgrade_threshold: String,
        jwt_token: &str
    ) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/levelRules", self.base_url);
        
        println!("[DEBUG] Updating level rule to: {}", url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("levelId", level_id);
        body.insert("levelName", level_name);
        body.insert("minPoints", min_points);
        body.insert("maxPoints", max_points);
        body.insert("coreTrait", core_trait);
        body.insert("uri", uri);
        body.insert("upgradeThreshold", upgrade_threshold);
        
        let response = match self.client
            .put(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] Update level rule HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] Update level rule HTTP request failed: {}", e);
                    return Err(format!("Failed to update level rule: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Update level rule response text: {}", text);
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read update level rule response: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| {
                println!("[ERROR] Update level rule JSON Parse Error: {}", e);
                println!("[ERROR] Raw response: '{}'", response_text);
                format!("Failed to parse response: {} | Raw response: {}", e, response_text)
            })?;

        Ok(parsed)
    }
    
    // 获取积分规则
    pub async fn get_credit_rules(&self, jwt_token: &str) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/creditRules", self.base_url);
        
        println!("[DEBUG] Fetching credit rules from: {}", url);
        
        let response = match self.client
            .get(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] Credit Rules HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] Credit Rules HTTP request failed: {}", e);
                    return Err(format!("Failed to fetch credit rules: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Credit Rules response text: {}", text);
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read credit rules response text: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        // Debug: Print the raw response text
        println!("[DEBUG] Credit Rules API Response Text: {}", response_text);
        println!("[DEBUG] Response length: {} characters", response_text.len());
        
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        // Try to handle malformed response with multiple JSON objects
        let cleaned_response = if response_text.contains("}{") {
            println!("[DEBUG] Detected concatenated JSON responses, attempting to extract first valid JSON");
            
            // Split by }{ and try to parse the first part
            let parts: Vec<&str> = response_text.split("}{").collect();
            
            if let Some(first_part) = parts.first() {
                let mut first_json = first_part.to_string();
                if !first_json.ends_with('}') {
                    first_json.push('}');
                }
                
                println!("[DEBUG] Attempting to parse first JSON part: {}", first_json);
                
                // Try to parse the first JSON
                match serde_json::from_str::<serde_json::Value>(&first_json) {
                    Ok(parsed) => {
                        println!("[DEBUG] Successfully parsed first JSON part");
                        return Ok(parsed);
                    }
                    Err(e) => {
                        println!("[DEBUG] Failed to parse first JSON part: {}", e);
                    }
                }
            }
            
            // If that fails, try the second part
            if parts.len() > 1 {
                let second_part = format!("{{{}", parts[1]);
                println!("[DEBUG] Attempting to parse second JSON part: {}", second_part);
                
                match serde_json::from_str::<serde_json::Value>(&second_part) {
                    Ok(parsed) => {
                        // Check if this is an error response
                        if let Some(status) = parsed.get("status") {
                            if status == 0 {
                                if let Some(msg) = parsed.get("msg") {
                                    return Err(format!("API Error: {}", msg.as_str().unwrap_or("Unknown error")));
                                }
                            }
                        }
                        return Ok(parsed);
                    }
                    Err(e) => {
                        println!("[DEBUG] Failed to parse second JSON part: {}", e);
                    }
                }
            }
            
            // If all parsing attempts fail, return the original response for standard parsing
            response_text
        } else {
            response_text
        };

        let parsed: serde_json::Value = serde_json::from_str(&cleaned_response)
            .map_err(|e| {
                println!("[ERROR] JSON Parse Error: {}", e);
                println!("[ERROR] Raw response causing parse error: '{}'", cleaned_response);
                format!("Failed to parse response: {} | Raw response: {}", e, cleaned_response)
            })?;

        Ok(parsed)
    }
    
    // 添加积分规则
    pub async fn add_credit_rule(
        &self,
        level_range_start: String,
        level_range_end: String,
        behavior_desc: String,
        points: String,
        limit_desc: String,
        sort_order: String,
        jwt_token: &str
    ) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/creditRules", self.base_url);
        
        println!("[DEBUG] Adding credit rule to: {}", url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("levelRangeStart", level_range_start);
        body.insert("levelRangeEnd", level_range_end);
        body.insert("behaviorDesc", behavior_desc);
        body.insert("points", points);
        body.insert("limitDesc", limit_desc);
        body.insert("sortOrder", sort_order);
        
        let response = match self.client
            .post(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] Add credit rule HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] Add credit rule HTTP request failed: {}", e);
                    return Err(format!("Failed to add credit rule: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Add credit rule response text: {}", text);
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read add credit rule response: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| {
                println!("[ERROR] Add credit rule JSON Parse Error: {}", e);
                println!("[ERROR] Raw response: '{}'", response_text);
                format!("Failed to parse response: {} | Raw response: {}", e, response_text)
            })?;

        Ok(parsed)
    }
    
    // 更新积分规则
    pub async fn update_credit_rule(
        &self,
        credit_id: String,
        level_range_start: String,
        level_range_end: String,
        behavior_desc: String,
        points: String,
        limit_desc: String,
        sort_order: String,
        jwt_token: &str
    ) -> Result<serde_json::Value, String> {
        let url = format!("{}/settings/creditRules", self.base_url);
        
        println!("[DEBUG] Updating credit rule to: {}", url);
        
        // 创建请求体
        let mut body = std::collections::HashMap::new();
        body.insert("creditId", credit_id);
        body.insert("levelRangeStart", level_range_start);
        body.insert("levelRangeEnd", level_range_end);
        body.insert("behaviorDesc", behavior_desc);
        body.insert("points", points);
        body.insert("limitDesc", limit_desc);
        body.insert("sortOrder", sort_order);
        
        let response = match self.client
            .put(&url)
            .header("Authorization", format!("Bearer {}", jwt_token))
            .header("Content-Type", "application/json")
            .json(&body)
            .send()
            .await {
                Ok(resp) => {
                    println!("[DEBUG] Update credit rule HTTP request successful, status: {}", resp.status());
                    resp
                }
                Err(e) => {
                    println!("[ERROR] Update credit rule HTTP request failed: {}", e);
                    return Err(format!("Failed to update credit rule: {}", e));
                }
            };

        let response_text = match response
            .text()
            .await {
                Ok(text) => {
                    println!("[DEBUG] Update credit rule response text: {}", text);
                    text
                }
                Err(e) => {
                    println!("[ERROR] Failed to read update credit rule response: {}", e);
                    return Err(format!("Failed to read response: {}", e));
                }
            };
            
        if response_text.trim().is_empty() {
            return Err("服务器返回空响应".to_string());
        }

        let parsed: serde_json::Value = serde_json::from_str(&response_text)
            .map_err(|e| {
                println!("[ERROR] Update credit rule JSON Parse Error: {}", e);
                println!("[ERROR] Raw response: '{}'", response_text);
                format!("Failed to parse response: {} | Raw response: {}", e, response_text)
            })?;

        Ok(parsed)
    }
}